// packageC/pages/takeOutIndex/takeOutIndex.js
const app = getApp()
const common = require('../../../public.js')
Page({
    /**
     *   页面的初始数据
     */
    data: {
        shareShopCar:'',// 2不共享 1共享
        totalNormalPrice:0,
        totalProfitPrice:0,
        totalNoJoinVipPrice:0,
        delSurplusUse:false,// 只处理一次
        storeCardId:'',
        appletsList:[],// 只动态请求一次 权益类目(左侧)
        rightShopList:[],// 只动态请求一次  权益商品列表(右侧)
        // hasRequestProfitAPI:false,// true:已请求权益商品相关接口 false：未请求权益商品相关接口
        hasProfitShop:false,// true:有权益商品 false：无权益商品
        appletsSelectCount:0,
        currentDishFlavorStr:'',
        showOpeCount:false,// true显示加减，false显示加入购物车按钮
        car_Add_ope:true,
        localGoodsCount:0,
        addCount:0,
        recordFixed:false,
        currentNum:null,
        numList:[],
        needList:[],
        eatImage:[],
        showSelectPersonPage:'',// 1展示人数选择页；2展示点餐页
        needTotalPrice:0.00,
        timer:'',
        getStoreIdAndUserInfoTimer:'',
        cartList:[],
        currentSelectNum:1,
        deskName:'',
        storeName:'',
        // 非得问问
        hasBuy:false,
        cardVipJson:"",
        postPrice:0.00,
        standardType:false,
        getHasSelectShopItemIdAndCountList:[],// 全部食物赋个数专用 以及 购物车里的全部商品列表
        rightShopCount:0,
        leftBadgeList:[],
        allAttrValueList:[], // 当前商品的所有sku信息
        currentItem:[], // 当前商品选中的某一个sku的信息
        TableId:'',
        value: 5, 
        shopCarShow: false,
        userInfo: {},
        orderList: ['点餐', '评价', '商家', '攻略'],
        actIndex: 0,
        cateLeftList: [], //左边列表
        dealDefaultItemList: [],
        activeId: -1, //左边   和右边的storeCid对应
        toView: '', //滚动目标f
        isCollected: false,
        clickShow: false,//监听左侧菜单栏是否点击
        guigeShow: false, //规格
        okHeight: 0,
        showImg: false,
        pageNum: 1,
        showStoreCoupons: false,
        isLoadingBusy: false, // 标记是否正在加载更多数据
        storeCouponsList: [], //店铺优惠券列表
        canLoad: true,
        flagHeight:true,
        isLoadingBusy: false,
        selectImg:'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/collect_icon_select.png',
        notselectImg:'http://feiyangimage.oss-cn-shanghai.aliyuncs.com/wxApplets/icon/collect_icon.png'
    },
    click_album(e){
       let currentIndex = e.currentTarget.dataset.index
       wx.navigateTo({
         url: '/packageA/pages/photoAlbum/photoAlbum?arr='+ JSON.stringify(this.data.shopInfo.backUpPicList) 
          + '&currentIndex=' + currentIndex
         ,
       })
    },
    //  去详情页
    toDetail(e) {
        // console.log('22222');
        // console.log(e.currentTarget.dataset.item, "jjjjooooo")
        let item = JSON.stringify(e.currentTarget.dataset.item)
        wx.navigateTo({
            url: '/pages/coupons/useCoupons/index?&from=company' + '&item=' + item,
        })
    },
    receiveStoreConpons(e) {
        let that = this
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }
        common.post("/discountCoupon/getShopCoupon", tempJson, function (res) {
            if (res.status == 200) {
                wx.showToast({
                    title: '领取成功',
                    icon: "none"
                })
                that.setData({
                    storeCouponsList: []
                }, () => {
                    that.getStoreCoupons(that.data.storeId, true)
                })

            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '领取失败',
                    icon: "none"
                })
            }
        })
    },
    // 店铺优惠券列表
    getStoreCoupons(refresh = true) {
        const that = this
        if (refresh) {
            this.data.canLoad = true
        }
        if (that.data.canLoad) {  //可以加载
            if (!refresh && this.data.isLoadingBusy) {
                return
            }
            this.setData({
                isLoadingBusy: true
            })
            const params = {
                storeId: that.data.storeId,
                pageNum: refresh ? 1 : that.data.pageNum + 1,
                status: 4
            }
            common.post("/discountCoupon/showDiscoutCouponList", params, function (res) {
                if (res.status === 200) {
                    that.data.pageNum = params.pageNum
                    if (res.data.result_list != '' || res.data.result_list.length != 0) {
                        that.setData({
                            storeCouponsList: [...that.data.storeCouponsList, ...res.data.result_list],
                        })
                    } else {
                        if (that.data.pageNum == 1) {
                            that.setData({
                                storeCouponsList: []
                            })
                            return
                        }
                        that.setData({
                            canLoad: false,
                        })
                    }

                }
            }, function () {
                that.setData({
                    isLoadingBusy: false
                })
            })
        }

    },
    to_coupfn() { this.setData({ showStoreCoupons: true }) },
    // 电话
    callPhone() {
        wx.makePhoneCall({
            phoneNumber: this.data.shopInfo.store.mobile,
            fail: function () { }
        })
    },
    checkAddress() { //点击地址按钮
        if (!this.data.shopInfo.store.xpoint || !this.data.shopInfo.store.ypoint) {
            common.showToast('商家未设置位置信息')
            return
        }
        let lon = parseFloat(this.data.shopInfo.store.xpoint)
        let lat = parseFloat(this.data.shopInfo.store.ypoint)
        wx.openLocation({
            latitude: lat,
            longitude: lon,
            name: this.data.shopInfo.store.name ? this.data.shopInfo.store.name : null,
            address: this.data.shopInfo.store.address ? this.data.shopInfo.store.address : null,
            scale: 18,
            fail: () => {
                wx.showToast({
                    title: '无地址信息',
                    icon: 'none'
                })
            }
        })
    },
    // 触底效果
    fnLower(e) {
        this.gong(false)
    },
    gong(refresh = false) {
        const that = this
        if (this.data.isLoadingBusy) {
            return
        }
        const pageNum = refresh ? 1 : this.data.pageNum + 1
        let tempJson = {
            pageSize: 10,
            pageNum,
            storeId: this.data.storeId
        }
        common.post('/storeArticle/getStoreArticleListForOneStore', tempJson,
            function (res) {
                that.data.pageNum = pageNum
                if (res.status === 200) {
                    that.setData({
                        articleList: res.data.list,
                        articleLists: refresh ? res.data.list : [...res.data.list, ...that.data.articleLists]
                    }, () => {
                        that.stopFn(res)
                    })
                } else {
                    // common.showRequestErrMsg(res)
                    that.stopFn(res)
                }
            },
            function () {
                // that.setData({
                //     isLoadingBusy: false
                // })
            })
    },
    // 没有数据不掉接口
    stopFn(res) {
        const that = this
        if (res.data && res.data.list !== []) {
        } else {
            that.setData({
                isLoadingBusy: true
            })
        }
    },
    // 图片预览
    preview(event) {
        let { nindex, windex } = event.currentTarget.dataset
        // console.log(nindex, windex)
        let pic_ce = this.data.commentList[windex].picUrls
        this.setData({
            pic_ce,
            current: nindex,
            showImg: true
        })
    },
    goDetails(e) {
        return;
        let itemId = e.currentTarget.dataset.item.id
        wx.navigateTo({
            url: `/packageC/pages/takeoutDetail/takeoutDetail?itemId=${itemId}&storeId=${this.data.storeId}`,
        })

    },

    // 获取购物车数量
    getCartNum(flag = false) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token,
            storeDeskId:that.data.TableId,
        }
        // console.log('---__---',tempJson);
        common.wxRequest(that.data.shareShopCar==2?'/cart/listByStoreSku':'/cart/listForStoreDeskSku', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            
            // console.log('bbbbbb---', res);
            if (res.status === 200) {
                let totalPrice = 0;
                let totalNum = res.data.totalNum
                let totalNormalPrice = 0;
                let totalProfitPrice = 0;
                let totalNoJoinVipPrice = 0;
                
                res.data.list.map((item, index) => {
                    if(item.itemCard=="2"){// 是否会员卡商品，1：会员卡商品，2：普通商品
                     
                        if(parseInt(item.payRateFlag) == 0){// 不参与会员折扣 
                            // console.log('不参与',index);
                            totalNoJoinVipPrice = item.num * item.price + totalNoJoinVipPrice;
                        }else{
                            // console.log('参与',index);
                            totalNormalPrice = item.num * item.price + totalNormalPrice;
                        }
                    }else{
                        totalProfitPrice = item.num * item.price + totalProfitPrice;
                    }
                    totalPrice = item.num * item.price + totalPrice
                })
                // console.log('購物車000=--处理后---',res.data);
                // console.log('totalNormalPrice---',totalNormalPrice,"++++totalProfitPrice",totalProfitPrice,"---totalNoJoinVipPrice",totalNoJoinVipPrice);
                that.setData({
                    cartList: res.data.list,
                    cartNum: totalNum,            
                    totalNormalPrice,
                    totalNoJoinVipPrice,
                    totalProfitPrice,
                    // goodsCount: 1,
                    totalPrice
                },()=>{
                    // console.log('价格---',that.data.totalPrice);
                })

            } else {
                that.setData({
                    cartList: [],
                    cartNum: 0,
                    totalNormalPrice:0,
                    totalNoJoinVipPrice:0,
                    totalProfitPrice:0,
                    // goodsCount: 1,
                    totalPrice: 0
                })
                if (!flag) {
                    wx.showToast({
                        icon: 'none',
                        title: res.msg ? res.msg : '添加失败',
                    })
                }

            }
        }, () => {
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // 获取左边类目及个数、右边列表、给历史选中增加selectNum和selectCardId属性
    getUserSelectInfo(tempItem,type){
        
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            // xpoint: this.data.lat,
            // ypoint: this.data.lon,
            storeDeskId:that.data.TableId,
            token: that.data.token,
            userId: that.data.userInfo.id,
        }
        common.get('/store/getStoreClassifyListAndAllItemForEat', tempJson, res => {
            // console.log('getStoreClassifyListAndAllItemForEat返回内容为--',res);
            var dealList = res.data.defaultItemList;
            var tempList = res.data.storeCatList;
            // 给左侧菜单增加hasShop属性
            if(tempList.length|| !tempList){
                for(var i = 0; i < tempList.length;i++){
                    var item1 =  tempList[i];
                    for(var j = 0; j < dealList.length;j++){
                        var item2 =  dealList[j];
                        if(item1.id == item2.storeCid){
                            item1.hasShop = true;
                        }
                    }
                }
            }else{
                var tempList = [];
            }
            
            for(var i = 0; i < tempList.length;i++){
                if(!tempList[i].hasShop){
                    tempList.splice(i,1);
                    i--;
                }
            }
            // console.log('tempList=+', tempList)
            that.unionDataFunc(tempList,dealList);

        })
    },
    addFinalFunc(item){
        // console.log('---新--',item);
        var that = this;
        var tempList = that.data.dealDefaultItemList;
        // console.log('加---',tempList);
       
        for(var i = 0;i < tempList.length;i++){
            if(item.id == tempList[i].id){
                tempList[i].selectNum =  tempList[i].selectNum+1;
            }
        
        }

        that.setData({
            dealDefaultItemList: tempList,
        })
    },
    minusFinalFunc(item){
        // console.log('---2新--',item);
        var that = this;
        var tempList = that.data.defaultItemList;
       
        for(var i = 0;i < tempList.length;i++){
            if(item.id == tempList[ i].id){
                tempList[i].selectNum =  tempList[i].selectNum-1;
            }
         
        }
        that.setData({
            dealDefaultItemList: tempList,
        })
    },
    // 店铺详情
    shopInfo(type) {
        var that = this
        var tempJson = {
            storeId: that.data.storeId,
            xpoint: this.data.lat,
            ypoint: this.data.lon,
            xcFlag: '0' //是否含有携程门票 0不含有
        }
        common.get('/store/mainPageInfo', tempJson, res => {

            var tempImageList = [];
            if(res.data.store.eatImage){
                var json = {imgUrl:res.data.store.eatImage};
                tempImageList.push(json);
            }
            
            for (let i = 0; i < res.data.couponList.length; i++) {
                that.setData({
                    industryType: res.data.store.industryType
                })
            }
            if (res.data.commentList) {
                for (var i = 0; i < res.data.commentList.length; i++) {
                    res.data.commentList[i].addTime = that.time(res.data.commentList[i].addTime)
                }
            }
            
            var tempList = res.data.itemCatList2.storeCatList;
            // console.log('主页里---',tempList);
            // console.log('角标i里---',this.data.leftBadgeList);
            for(var i = 0;i<tempList.length;i++ ){
                for(var j = 0;j < this.data.leftBadgeList.length;j++){
                    if(parseInt(this.data.leftBadgeList[j].storeCid)==tempList[i].id){
                        tempList[i].num = this.data.leftBadgeList[j].num;
                    }
                }
            }
            // console.log('aaa主页里---',tempList);
            this.setData({

                commentList: res.data.commentList,

                activeId: type==2?9999:(res.data.itemCatList2.storeCatList.length > 0 ? res.data.itemCatList2.storeCatList[0].id : ''),
                couponList: res.data.couponList,
                shopInfo: res.data,
                eatImage:tempImageList,

            }, () => {
                console.log('走到这里mainPageInfo没问题')

            })

        })
    },
    calFunc(){
        var that = this;
         // 计算右侧商品高度
        wx.createSelectorQuery().selectAll('.cessss').boundingClientRect(function (rect) {//selectAll会选择所要含有该类名的盒子
        }).exec(function (res) {
            // console.log(res,"454444444s")
            that.heightArry(res)
        })
    },
    toArticleDetail(e) {
        const item = e.currentTarget.dataset.item
        wx.navigateTo({
            url: '/pages/discovery/articleDetail/index?id=' + item.id +
                '&storeName=' + item.storeName +
                '&title=' + item.title +
                '&createTime=' + item.createTime +
                '&storeImg=' + item.storeImg
        })
    },

    queryCollection() {
        var that = this
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/collected", tempJson, function (res) {
            // 当前接口200是关注，非200是未关注
            that.setData({
                isCollected: res.data
            })
        });
    },
    // 是否收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })
    },
    // 时间戳
    time(time) {
        return common.dateFormat('yyyy-MM-dd HH:mm', time)
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        // https://api.feiyanghy.com?scanOrderMeal&storeId=8680&TableId=78&deskName=测试（勿做）&seat=2&shareShopCar=1&extendType1=2&extendType2=2
        clearInterval(this.data.timer);
        console.log('7.20--a扫码商品--',options);
        let screenHeight = wx.getSystemInfoSync().windowHeight
        let okHeight = (screenHeight - 88 - 110 - 80 - 65)
        const that = this
        this.setData({
            toView: 'a1',
        })
        // 返回按钮
        let capsule = wx.getMenuButtonBoundingClientRect()
        this.setData({
            okHeight,
            height: capsule.height,
            top: capsule.top,
         
        })

        if (options.q) {
            let scan_url = decodeURIComponent(options.q);
            console.log("进来0")
  
            let pos1 = scan_url.indexOf("storeId="); // 
            let pos2 = scan_url.indexOf("&TableId="); // 
            let pos3 = scan_url.indexOf("&deskName="); // 
            let pos4 = scan_url.indexOf("&seat="); // 
            let pos5 = scan_url.indexOf("&shareShopCar="); // 
            let pos6 = scan_url.indexOf("&extendType1="); // 
            let pos7 = scan_url.indexOf("&extendType2="); // 

            var storeId = scan_url.substring(pos1+8, pos2)
            var TableId = scan_url.substring(pos2+9, pos3)
            var deskName = scan_url.substring(pos3+10, pos4)
          console.log('5555---',pos5);
          var seat;
          var shareShopCar;
          var extendType1;
          var extendType2;
          if(pos5==-1){
            var seat = scan_url.substring(pos4+6, scan_url.length)

          }else{
           seat = scan_url.substring(pos4+6, pos5)

           shareShopCar = scan_url.substring(pos5+14, pos6)
           extendType1 = scan_url.substring(pos6+13, pos7)
           extendType2 = scan_url.substring(pos7+13, scan_url.length)
          }
          
 
            options.storeId = storeId;
            options.TableId = TableId;
            options.deskName = deskName;
            options.seat = seat;
            options.shareShopCar = shareShopCar;
            options.extendType1 = extendType1;
            options.extendType2 = extendType2;
            console.log('赋值后--storeId--',options.storeId,'---TableId',options.TableId,'---deskName',options.deskName,'---seat',options.seat);
        var list = [];
        for(var i = 0;i < parseInt(options.seat);i++){
            var json = {};
            json.id = i+1;
            list.push(json);
        }

        that.setData({
            storeId:options.storeId,
            TableId: options.TableId,
            deskName:options.deskName,
            seat:options.seat,
            numList:list,
        })


        // 用户信息
        common.getLocalUserInfo((success, data) => {
            if (success) {
                this.setData({
                    userInfo: data.user,
                    token: data.token,
                    storeId:options.storeId,
                    TableId: options.TableId,
                    openid: data.openid,
                  
                    // currentSelectNum:options.currentSelectNum,
                 
                    storeName:options.name,
                    shareShopCar:options.shareShopCar,
                    extendType1:options.extendType1,
                    extendType2:options.extendType2,
                    // console.log('店铺id',options.id,'----桌号---',options.tableId,'----deskName----',options.deskName,'===storeName=',options.name);
                }, () => {
                    console.log('aaa执行了-----',that.data.shareShopCar);
                    this.clickCollect()  //是否收藏
                    this.gong(true)
                    this.queryCollection()
                    this.getCartNum(true)
                    this.recordUserFromFunc(options.storeId);
                    // console.log('店铺id',options.id,'----桌号---',options.tableId,'----deskName----',options.deskName,'===storeName=',options.name);
                    that.getStoreCoupons(options.storeId, true)
                    // that.getCardForTakeawayFunc(options.storeId, true)
                   


                    
                })
            }
        }, true)
return;
    }
    console.log('走非options.q逻辑')
    // return
    var list = [];
    for(var i = 0;i < parseInt(options.seat);i++){
        var json = {};
        json.id = i+1;
        list.push(json);
    }
    that.setData({
        storeId:options.storeId,
        TableId: options.TableId,
        deskName:options.deskName,
        seat:options.seat,
        numList:list,
     
    },()=>{
        console.log('--dd---',that.data.TableId);
    })

    common.getLocalUserInfo((success, data) => {
        if (success) {
            // data.user.id = 26072 
            this.setData({
                userInfo: data.user,
                token: data.token, // 5e7cc2f4f89a12edd4f49ba5942088f4 ,
                openid: data.openid,
              
                // currentSelectNum:options.currentSelectNum,
            
                storeName:options.name,
                shareShopCar:options.shareShopCar,
                extendType1:options.extendType1,
                extendType2:options.extendType2,
                
                // console.log('店铺id',options.id,'----桌号---',options.tableId,'----deskName----',options.deskName,'===storeName=',options.name);
            }, () => {
                console.log('bbbb执行了-----',that.data.shareShopCar,"fff---",that.data.extendType1,"===ggg",that.data.extendType2);
                this.clickCollect()  //是否收藏
                this.gong(true)
                this.queryCollection()
                this.getCartNum(true)
                // console.log('店铺id',options.id,'----桌号---',options.tableId,'----deskName----',options.deskName,'===storeName=',options.name);
                that.getStoreCoupons(options.storeId, true)
                this.recordUserFromFunc(options.storeId);
                // that.getCardForTakeawayFunc(options.storeId, true)
               


                
            })
        }
    }, true)

    },

    onShow() {
        var that = this;
        console.log('onShow---',that.data.shareShopCar);

        wx.hideHomeButton();  //隐藏home/返回主页按钮
        that.data.getStoreIdAndUserInfoTimer = setInterval(function() {
            if(that.data.storeId){
              console.log('获取到，定时器关闭',that.data.shareShopCar);
              clearInterval(that.data.getStoreIdAndUserInfoTimer);
            console.log('看不到该行代码，说明定时器报错了')
                    that.requestOnceFunc();
            }else{
                console.log('没获取到，定时器不关闭');
            }
          }, 100);
            //    // 定位
            //   that.getLocation()
 
    },

    recordUserFromFunc(storeId){
        var that = this;
        var tempJson = {
            userId: that.data.userInfo.id,
            storeId: storeId
        };
      
        common.post("/user/saveStoreUserFromEatScan", tempJson, function (res) {

        })
    },
    judgeSelectPersonFunc(storeId) {
        console.log('judgeSelectPersonFunc函数体')

        var that = this;
        that.setData({
            showSelectPersonPage:2
        },()=>{
            if(that.data.shareShopCar==2){// 不共享 
                that.getCartNum(true)
    
                that.getHasSelectShopItemIdAndCountFunc();
                
            }else{// 共享
                console.log('定时器快开始了')
                that.socketFunc();
            }
            that.getNeedList(that.data.storeId)
        })
    },
    socketFunc(){
        var that = this;
        that.data.timer = setInterval(function() {
            
            // console.log('111哈哈哈哈哈哈');
            
            that.getCartNum(true)
   
            that.getHasSelectShopItemIdAndCountFunc();
            // 要执行的操作
        }, 1500);
    },
    // // 获取当前定位
    // getLocation() {
        
    //     app.getLocation(
    //         (data) => {
    //             this.setData({
    //                 lon: data.longitude,
    //                 lat: data.latitude
    //             }, () => {
    //                 this.shopInfo();
                    
    //                 this.requestOnceFunc();
                   

    //                 // this.getLeftBadgeNum(true)
                   
    //             })
    //         },
    //         (err) => {
    //             // 定位失败回调
    //             this.setData({
    //                 refreshing: false
    //             })
    //         })
    // },

    getHasSelectShopItemIdAndCountFunc(tempItem,type) {
        const that = this
        let tempJson = {
            storeId: that.data.storeId,
            userId: that.data.userInfo.id,
            token: that.data.token,
            storeDeskId:that.data.TableId,
        }
        // console.log('type---',type);
        // console.log('-jjjj--',tempJson);
        common.wxRequest(that.data.shareShopCar==2?'/cart/listByStoreSku':'/cart/listForStoreDeskSku', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            // console.log('ccccc获取已选商品的id和个数',res);
            if (res.status === 200) {
          
                that.setData({
                    getHasSelectShopItemIdAndCountList:res.data.list
                },()=>{
                    // 获取左边类目及个数、右边列表、给历史选中增加selectNum和selectCardId属性
                    // console.log('fggg-');
                    that.getUserSelectInfo(tempItem,type);
                })
              
            
            } else {

                that.setData({
                    getHasSelectShopItemIdAndCountList:[]
                },()=>{
                    // 获取左边类目及个数、右边列表、给历史选中增加selectNum和selectCardId属性
                    that.getUserSelectInfo(tempItem,type);
                })
              

      
             
            }
        }, () => {
            that.setData({
                isShowLoader: false  //购物车加载
            })
        })
    },
    // 右侧商品的高度
    heightArry(res) {
        let h = 0;
        let heightArr = [];
        res[0].forEach((item) => {
            h += item.height;
            heightArr.push(h);
        })
        this.setData({ heightArr: heightArr })
    },
    // 滚动事件
    Right_Scroll(e) {
        const that = this
        if (!that.data.clickShow && typeof(that.data.dealDefaultItemList) === 'object') {
            // this.data.dealDefaultItemList = undefined
            let scrollHeight = e.detail.scrollTop;
            let index = this.calculateIndex(this.data.heightArr, scrollHeight);
            // console.log('类型', typeof(that.data.dealDefaultItemList))
            // TODO 以下报undefined is not an object (evaluating \'this.data.dealDefaultItemList[a].storeCid\')问题
            // console.log(index,'--==',this.data.dealDefaultItemList,'++==', this.data.dealDefaultItemList[index].storeCid)
            this.setData({
                activeId: that.data.dealDefaultItemList[index].storeCid
            }, () => {
            })
        }
        this.setData({
            clickShow: false
        })

    },
    // 计算左边选中的下标
    calculateIndex(arr, scrollHeight) {
        let index = '';
        for (let i = 0; i < arr.length; i++) {
            if (scrollHeight >= 0 && scrollHeight < arr[0]) {
                index = 0;
            } else if (scrollHeight >= arr[i - 1] && scrollHeight < arr[i]) {
                index = i;
            }
        }
        return index;
    },
    // 二级分类点击
    clickItem(e) {
        // console.log('eee-----',e.currentTarget.dataset.id);
        const that = this
        this.setData({
            activeId: e.currentTarget.dataset.id,
            toView: e.currentTarget.dataset.id,
            clickShow: true
        }, () => {

        })
    },
    // tabs切换
    click_item(e) {
        let index = e.currentTarget.dataset.index
        this.setData({
            actIndex: index
        })
    },
    // 点击收藏
    clickCollect() {
        let that = this
        let param = that.data.isCollected ? 'delete' : 'add'
        var tempJson = {
            token: that.data.token,
            userId: that.data.userInfo.id,
            storeId: that.data.storeId
        };
        common.post("/store/favo/" + param, tempJson, function (res) {
            res.status == 200 && that.queryCollection()
        })

    },
    // 选规格
    go_guige(e) {
        let { id, item } = e.currentTarget.dataset
        console.log('选中json',item,'个数--selectNum',item.selectNum);
        if(item.selectNum==undefined){
            // console.log('111111');
        }else{
            // console.log('2232222');
        }
        this.setData({
            showOpeCount:false,
            currentGuideJson:item,
            localGoodsCount:item.selectNum==undefined?0:item.selectNum,
            itemId: id,
            // goodsCount:12,
       
  
        },()=>{
         
            this.setData({
                guigeShow: true,
            },()=>{
                this.getItemSkuListFunc(item);
            })
        })
        // this.clickGetDishAttrList(e)
      
    },
    onClose() {
        this.setData({
            guigeShow: false
        });
    },
    // 商品规格
    clickGetDishAttrList(e) {
        let that = this
        let { id, item } = e.currentTarget.dataset
        let tempJson = {
            itemId: id,

        }
        that.setData({
            itemId: id,
            goodsNei: item
        })
        common.post("/item/getDishAttrList", tempJson, function (res) {
            // console.log(res,"545466666222222222")
            let checkedStr = '';
            for (let i = 0; i < res.data.length; i++) {
                if (i !== res.data.length - 1) {// 不是最后一个，就拼接/
                    checkedStr = checkedStr + res.data[i].attrValueList[0].attrValue + '/'
                } else {// 最后一个，不拼接/
                    checkedStr = checkedStr + res.data[res.data.length - 1].attrValueList[0].attrValue
                }

            }
            var tempList = res.data;
            for(var i = 0;i < tempList.length;i++){
                var twoList = tempList[i];
                for(var j =0;j < twoList.attrValueList.length;j++){
                    twoList.attrValueList[j].select = false;
                }
            }
            // console.log('---checkedStr--',checkedStr);
            that.setData({
                allAttrValueList: tempList,
                currentDishFlavorStr: checkedStr
            },()=>{
                // console.log('----++====',tempList);
            })
        })
    },
   
    getItemSkuListFunc(item) {
        let that = this

        let tempJson = {
            itemId: item.id,
       
        }
        common.post("/item/getItemSkuList", tempJson, function (res) {
            // console.log('getItemSkuList---',res);
            if (res.status == 200) {           
                    for(var j =0;j < res.data.length;j++){
                        res.data[j].select = j==0?true:false; // 默认选中第0个sku
                    }
               that.setData({
                allAttrValueList:res.data,
                currentItem:res.data.length?res.data[0]:{}
               },()=>{
                //    console.log('ffffcurrentItem----',that.data.currentItem);
                   that.getItemCartCountForStoreDeskFunc(that.data.currentItem.id);
               })
            } else {
                common.showRequestErrMsg(res)
            }
        })
    },
    // 根据某个sku的id，获取该sku在购物车中数量
    getItemCartCountForStoreDeskFunc(dishFlavorStr) {
        let that = this
        // let { id, item } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            token: that.data.token,
            storeDeskId:that.data.TableId,
            itemId:that.data.currentGuideJson.id,
            dishFlavor:dishFlavorStr,// '粉红色/小号'

        }

        common.post("/cart/getItemCartCountForStoreDesk", tempJson, function (res) {
            // console.log('获取商品在购物车中数量---',res)
            
            that.setData({
               showOpeCount:res.data?true:false,  
               localGoodsCount:res.data     // 某个规格的数量     
            })
      
        })
    },
    // 添加购物车
    submitAddSkuCart() {
        const that = this
        const itemId = this.data.itemId
 
        const rightShopList = this.data.rightShopList;
        const shopItem = rightShopList.find(item => item.id === that.data.itemId && item.surplusUse === 0);
        if (shopItem) {
             common.showToast('已到最大权益次数!');
            return true;
        }


        var checkedStr ='';
            for(var j =0;j < that.data.allAttrValueList.length;j++){
                if(that.data.allAttrValueList[j].select == true){
                    checkedStr = that.data.allAttrValueList[j].id;
                }
              
            }
  
         // dishFlavorStr = dishFlavorStr.substring(0, dishFlavorStr.length - 1);
        //  console.log('嘻嘻嘻hhh-',checkedStr);
         if(!checkedStr){
            return common.showToast('请补全规格!')
         }
      

        let tempJson = {
            // dishFlavor: that.data.checkedAttr,
            // dishFlavor:checkedStr,// checkedStr?checkedStr.slice(0, -1):''
            dishFlavor:that.data.currentItem.id,
            userId: that.data.userInfo.id,
            token: that.data.token,
            storeDeskId:that.data.TableId,
            itemId,
            num:1,// that.data.addCount
        }
        common.wxRequest(that.data.shareShopCar==2?'/cart/add':'/cart/addItemCartForStoreDesk', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                // that.closeAddCart()
                that.rightSurpususeFunc(itemId,1);
                that.getCartNum()  //获取
                that.getHasSelectShopItemIdAndCountFunc();
                // that.getLeftBadgeNum();
                that.setData({
                    // goodsCount: 1,
                    addCount:0,
                    showOpeCount:true,
                    localGoodsCount:1,
                })
                common.showToast('添加成功!')
                // wx.showToast({
                //     title: '添加成功!',
                // })
            } else {
                wx.showToast({
                    icon: 'loading',
                    title: res.msg ? res.msg : '添加+失败',
                })
            }
        })
    },
    normalDeleteCardFunc(num, cartId, item) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: item.id,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        // console.log('呼呼',tempJson);
        common.wxRequest(that.data.shareShopCar==2?'/cart/updateOneByCartId':'/cart/updateOneByCartIdForStoreDesk', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.rightSurpususeFunc(item.id,num);
                that.getCartNum()
                that.getHasSelectShopItemIdAndCountFunc(item,'minus');
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },


    normalAddCardFunc(tempItem,num) {
        const that = this
        let tempJson = {
          dishFlavor:tempItem.skuList?tempItem.skuList[0].id:'',//  因为现在所有的商品，发布时都需要填sku(至填一个)，且商品信息都在sku里，所以这里默认取第0个sku的信息的id
            // dishFlavor:'',
            userId: that.data.userInfo.id,
            token: that.data.token,
            itemId:tempItem.id,
            storeDeskId:that.data.TableId,
            num
        }
        common.wxRequest(that.data.shareShopCar==2?'/cart/add':'/cart/addItemCartForStoreDesk', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) { 
            if (res.status === 200) {
                that.rightSurpususeFunc(tempItem.id,num);
               that.getHasSelectShopItemIdAndCountFunc(tempItem,'add');
  
                that.closeAddCart()
                that.getCartNum()  //获取
                // that.getLeftBadgeNum();
                that.setData({
                    // goodsCount: 1,
                })
                common.showToast('添加成功!')
                // wx.showToast({
                //     title: '添加成功!',
                // })
            } else {
                wx.showToast({
                    icon: 'loading',
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    // 右侧剩余权益计算
    rightSurpususeFunc(idx,num){
        var returnValue = false
        var that = this;
        console.log('权益商品列表rightShopList---', this.data.rightShopList,'--idx', idx)
   
        if(num==1){// 增加
            for(var i = 0;i < this.data.rightShopList.length;i++){
                var shopItem = this.data.rightShopList[i];
                if(shopItem.id == idx){
                    shopItem.surplusUse = shopItem.surplusUse - 1;
                }
            }
        }else{// 减少
              for(var i = 0;i < this.data.rightShopList.length;i++){
                  var shopItem = this.data.rightShopList[i];
                    if(shopItem.id == idx){
                        shopItem.surplusUse = shopItem.surplusUse + 1;
                        if(shopItem.selectNum==1){
                            shopItem.selectNum = 0;
                        }
                    }
             }
        }
       
        

        that.setData({
            rightShopList:[...that.data.rightShopList]
        },()=>{
            // this.normalAddCardFunc(item, 1)
        })
    },
    closeAddCart() {
        this.setData({
            guigeShow: false
        })
    },
    // 点击购物车
    click_shoppcar() {
        this.setData({
            shopCarShow: true,
        }, () => {
            this.getCartNum()
        })
    },
    // 清空购物车    userId  cartIds  删除或者多个
    clearCart() {
        const that = this
        let arrList = []
        for (let i = 0; i < that.data.cartList.length; i++) {
            arrList.push(that.data.cartList[i].id)
        }
        that.clearProfitFunc();
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartIds: arrList.toString(),
            userId: that.data.userInfo.id,
            token: that.data.token,
            storeDeskId:that.data.TableId
        }
        common.wxRequest(that.data.shareShopCar==2?'/cart/deleteByCartId':'/cart/clearCartForStoreDesk', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                // that.onCloses()
                that.setData({
                    // needTotalPrice:0.00
                })
                that.getCartNum()
                that.getHasSelectShopItemIdAndCountFunc();
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },


    clearProfitFunc(){
        var that = this
        common.get('/userAnnualCard/checkIsBuyStoreAnnualCard', {
            userId: this.data.userInfo.id,
            storeId: that.data.storeId,
            token: this.data.token
        }, res => {
            // console.log('checkIsBuyStoreAnnualCard---',res)
    
            if(res.data){// 权益商品
                that.clearProfitShopFixDataFunc(res.data);
                that.setData({
                    // storeCardId:''
                })
            }
           
        })
    
    },
    clearProfitShopFixDataFunc(idx) {
        var that = this
        common.get('/userAnnualCard/getAllCardItemListForOneStoreApplets', {
            userId: this.data.userInfo.id,
            // cardId: idx,
            storeId:this.data.storeId,
            token: this.data.token
        }, res => {
            // console.log('getAllCardItemListForOneStoreApplets---',res.data)
            // cateLeftList
            var appletsList = [];
            var rightShopList = [];
           if(res.data){
    
            var json = {selectNums: 0, name: "会员权益", id: 9999}
            appletsList.push(json);
    
            for(var i = 0;i < res.data.length;i++){
                var rightItem = {};
                var item = res.data[i];
                rightItem.storeCid = 9999;
                rightItem.id = item.productId;
                rightItem.image = item.productImage;
                rightItem.price = item.productPrice;
                rightItem.title = item.productName;
                rightItem.surplusUse = item.surplusUse;
                rightItem.surplusUseFixed = item.surplusUse;
                rightItem.dishAttrList = item.dishAttrList;
                rightItem.skuList = item.skuList;
                rightItem.num = item.surplusUse;
                rightShopList.push(rightItem);
            }
    
           }
           that.setData({
            rightShopList:rightShopList,
            appletsList:appletsList,
           },()=>{
    
               
           })
    
    
        })
    },

    
    // 返回上页面
    goBack() {
        clearInterval(this.data.timer);
        const pages = getCurrentPages();
        const prevPage = pages[pages.length - 2]; //上一个页面
        // 从朋友圈进入的时候，页面栈为空，这里需要判断是否有上个页面
        if (prevPage) {
            wx.navigateBack({
                delta: 1
            })
        } else {
            wx.redirectTo({
                url: '/pages/index/index',
            })
        }
    },
    // 购物车关闭
    onCloses() {
        this.setData({
            shopCarShow: false
        })
    },
    //购物车减少一
    onminus(e) {
        let item = e.currentTarget.dataset.item
        let cartId = item.id
        // console.log(item, "lllllllllllllllllllllllllllllllllllllll")
        this.changeCartNum(-1, cartId, item.itemId)

    },
    //  购物车增加1
    onplus(e) {
        let { index, item } = e.currentTarget.dataset
        let cartId = item.id

            const rightShopList = this.data.rightShopList;
            const shopItem = rightShopList.find(item1 => item1.id === item.itemId && item1.surplusUse === 0);
            if (shopItem) {
            common.showToast('已到最大权益次数!');
                return true;
            }
        this.changeCartNum(1, cartId, item.itemId)
    },
    //购物车加一
    changeCartNum(num, cartId, itemId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            itemId: itemId,
            token: that.data.token,
            cartId,
            num,
            userId: that.data.userInfo.id,
        }
        common.wxRequest(that.data.shareShopCar==2?'/cart/updateOneByCartId':'/cart/updateOneByCartIdForStoreDesk', 'POST', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.getCartNum()
                that.getHasSelectShopItemIdAndCountFunc();
                that.dealCurrentProfitFunc(itemId,num);
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },

    dealCurrentProfitFunc(itemId,num){
        var that = this;
        for(var i = 0;i < this.data.rightShopList.length;i++){
            var shopItem = this.data.rightShopList[i];
            if(shopItem.id == itemId){
               if(num==1){// 增加操作
                shopItem.surplusUse = shopItem.surplusUse - 1;// 权益次数减少
               }else{// 减少操作
                shopItem.surplusUse = shopItem.surplusUse + 1;// 权益次数增加
                if(shopItem.selectNum==1){
                    shopItem.selectNum = 0;
                }
               }
            }
        }

        that.setData({
            rightShopList:[...that.data.rightShopList]
        },()=>{

        })
    },
    // 购物车输入改变
    onblur(e) {
        const that = this
        let { item } = e.currentTarget.dataset
        let num = e.detail.value
        let cartId = item.id
        that.inputCartNum(num, cartId, item.itemId)

    },
    //  输入input改变     userId cartId num   修改数量
    inputCartNum(num, cartId) {
        const that = this
        this.setData({
            isShowLoader: true
        })
        let tempJson = {
            cartId,
            num,
            userId: that.data.userInfo.id,
            token: that.data.token
        }
        common.wxRequest('/cart/updateNumByCartId', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
            if (res.status === 200) {
                that.onCloses()
                that.getCartNum()
            } else {
                wx.showToast({
                    title: res.msg ? res.msg : '添加失败',
                })
            }
        })
    },
    //    立即结算
    go_balance() {
        // return
        var that = this;
        if (this.data.cartNum == 0) {
            return
        }
        // wx.navigateTo({
        //     url: `/packageC/pages/takeoutOrder/takeoutOrder?storeId=${this.data.storeId}&totalPrice=${this.data.totalPrice}&storeId=${this.data.storeId}`,
        // })
        // console.log('清空定时器---',that.data.timer);
        clearInterval(that.data.timer);
        // co
        // var 
        wx.navigateTo({
            url: `/packageC/pages/scanMealOrder/scanMealOrder?storeId=${that.data.storeId}&TableId=${that.data.TableId}&deskName=${that.data.deskName}&name=${that.data.storeName}&currentSelectNum=${that.data.currentSelectNum}&totalPrice=${that.data.totalPrice}&totalNormalPrice=${that.data.totalNormalPrice}&totalProfitPrice=${that.data.totalProfitPrice}&totalNoJoinVipPrice=${that.data.totalNoJoinVipPrice}&storeCardId=${that.data.storeCardId}&shareShopCar=${that.data.shareShopCar}`,
        })
        // wx.navigateTo({
        //     url: `/packageC/pages/scanMealOrder/scanMealOrder?storeId=${this.data.storeId}&totalPrice=${this.data.totalPrice}&storeId=${this.data.storeId}`,
        // })
    },
    // 列表触底
    loadMore() {
        this.getStoreCoupons(false)
    },
    // 无规格---减少
    minusFunc(e){
        // console.log('无规格---减少');
        var item = e.currentTarget.dataset.item;
        this.normalDeleteCardFunc(-1, item.selectCardId, item) 
    },
       // 无规格---增加
    addFunc(e){
        // console.log('无规格---增加');
        // console.log("++++",e.currentTarget.dataset);
        var item = e.currentTarget.dataset.item;
        this.normalAddCardFunc(item, 1)
    },
    click_oneId(e) {
        let that = this

        // console.log('gggg----',e.currentTarget.dataset.index);
        // console.log('++++',e.currentTarget.dataset.item);

        var currentItem = e.currentTarget.dataset.item;
        // console.log("currentItem---",currentItem);
        // console.log('suoyou ---',that.data.allAttrValueList);
      
        var tempList = that.data.allAttrValueList;
        for(var i = 0;i < tempList.length;i++){
            var twoList = tempList[i];
            for(var j =0;j < twoList.attrValueList.length;j++){
                // twoList.attrValueList[j].select = false;
                if(twoList.attrValueList[j].id == currentItem.id){
                    if(twoList.attrValueList[j].attrId == currentItem.attrId){
                        for(var m =0;m < twoList.attrValueList.length;m++){
                            twoList.attrValueList[m].select = false;
                        }
                        twoList.attrValueList[j].select = true;
                    }
                    
                }
            }
        }

        this.setData({
            // allAttrValueList:that.data.allAttrValueList,
            allAttrValueList:tempList,
            oneId:currentItem.id,
            oneName:currentItem.attrValue,
        },()=>{
            var dishFlavorStr = '';
            for(var i = 0;i < that.data.allAttrValueList.length;i++){
                var twoList = tempList[i];
                for(var j =0;j < twoList.attrValueList.length;j++){
                    var items = twoList.attrValueList[j];
                    if(items.select){
                        dishFlavorStr = dishFlavorStr + items.attrValue + '/';
                    }
 
                }
            }
            if(dishFlavorStr){
                dishFlavorStr = dishFlavorStr.substring(0, dishFlavorStr.length - 1);
              }
            //   console.log('dishFlavorStr---',dishFlavorStr);
            // console.log('最新---',that.data.allAttrValueList);
            that.getItemCartCountForStoreDeskFunc(dishFlavorStr);
            that.setData({
                currentDishFlavorStr:dishFlavorStr
            })
        })
        return;
        let {
            couponid
        } = e.currentTarget.dataset
        let tempJson = {
            userId: that.data.userInfo.id,
            discountCouponId: couponid,
            source: 1, // 1为手动领取，2为系统群发
            token: that.data.token
        }

    },

    // 点击某个sku调用
    sku_click_oneId(e) {
        let that = this
        // console.log('gggg----',e.currentTarget.dataset.index);
        console.log('当前选中的sku++++',e.currentTarget.dataset.item);
        var currentItem = e.currentTarget.dataset.item;
        // console.log("currentItem---",currentItem);
        // console.log('suoyou ---',that.data.allAttrValueList);
        if(parseInt(that.data.currentGuideJson.unitFlag)==1&&currentItem.num==0){
          wx.showToast({
            icon: 'none',
            title: '数量库存不足',
          })
          return;
        }
        if(parseInt(that.data.currentGuideJson.unitFlag)==2&&currentItem.weight==0){
          wx.showToast({
            icon: 'none',
            title: '重量库存不足',
          })
          return;
        }
        var tempList = that.data.allAttrValueList;
        for(var j =0;j < tempList.length;j++){
            tempList[j].select = false;
        }
            for(var j =0;j < tempList.length;j++){
                if(tempList[j].id == currentItem.id){
                    // console.log('有符合的',tempList[j].id);
                    tempList[j].select = true;
                }
            }
        this.setData({
            currentItem,
            allAttrValueList:tempList,
            oneId:currentItem.id,
        },()=>{
            // console.log('最新---',that.data.allAttrValueList);
            that.getItemCartCountForStoreDeskFunc(that.data.currentItem.id);
        })
    },
    onStoreCouponosClose() { this.setData({ showStoreCoupons: false }) },

    inputChange1: function (options) {
        //获取输入框输入的内容
        let value = options.detail.value;
        // console.log("输入框输入的内容是 " + value)
        this.setData({
            rightShopCount:value
        })
      },
      getCardForTakeawayFunc(idx){
        
        var that = this
        let tempJson = {
            storeId: idx,
        
        }

        common.post('/userAnnualCard/getCardForTakeawayRec', tempJson, function (res) {
            // console.log('年5卡会员',res);
            if (res.status === 200) {
                that.setData({
                    cardVipJson:res.data,
                })
                if(res.data){
                    that.isPayFunc(res.data.id);
                
                }
            
            } else {
                // common.showRequestErrMsg(res)
            }
        }, function () {
           
        })
    },
     // 判断是否支付
  isPayFunc(idx) {
    var that = this
    common.get('/userAnnualCard/checkUserBoughtCard', {
        userId: this.data.userInfo.id,
        cardId: idx,
        token: this.data.token
    }, res => {
        // console.log(res)

        that.setData({
            
            hasBuy:res.status === 1?true:false,
        },()=>{
            // console.log('ssss---',that.data.hasBuy);
        })
   
    })
},



requestOnceFunc(){
    console.log('看到该行文字，初步判断初次加载白屏解决')
        var that = this
        common.get('/userAnnualCard/checkIsBuyStoreAnnualCard', {
            userId: this.data.userInfo.id,
            storeId: that.data.storeId,
            token: this.data.token
        }, res => {
            // console.log('checkIsBuyStoreAnnualCard---',res)
            // res.data = 117;

            if(res.data){// 权益商品
                console.log('权益商品执行1')
                that.profitShopFixDataFunc();
                console.log('权益商品执行2')
                that.reLists(res.data); 
                console.log('权益商品执行3')
                that.shopInfo(2); 
                console.log('权益商品执行4')
                that.setData({
                    storeCardId:res.data,
                })
            }else{// 非权益商品
               console.log('非权益商品执行1')
                that.shopInfo(1);
                // this.getHasSelectShopItemIdAndCountFunc();
                console.log('非权益商品执行2')
                that.judgeSelectPersonFunc();// 测试时，屏蔽改行代码，要打开上一行代码
                console.log('非权益商品执行3')
                that.getCardForTakeawayFunc(that.data.storeId);
                // that.setData({
                //     hasBuy:res.data?true:false,
                //     memeberSelect:res.data?true:false,
                // })


                // var json = {};
                // json.payRate = 1;
                // that.setData({
                //     cardVipJson:json
                // })
            }
           
        })

},
reLists(idx) {
    var that = this
    common.get('/userAnnualCard/getCardList', {
        cardId: idx
    }, res => {
        if (res.status === 200) {
            // console.log('33---',res);
         
            var tempData = res.data[0];
            if(tempData.payRate == 1){
                that.getCardForTakeawayFunc(that.data.storeId);
            }else{
                that.setData({
                    cardVipJson:tempData,
                    cardRate:tempData?tempData.payRate.toFixed(2)*100/10:1,
                    cardVipShow:tempData?true:false,
                    hasBuy:true,
                },()=>{
                    
                
                })
            }
             


                
        
        } else {
            common.showRequestErrMsg(res)
        }
    })
},
profitShopFixDataFunc() {
    var that = this
    common.get('/userAnnualCard/getAllCardItemListForOneStoreApplets', {
        userId: this.data.userInfo.id,
        // cardId: idx,
        storeId:this.data.storeId,
        token: this.data.token
    }, res => {
        // console.log('getAllCardItemListForOneStoreApplets---',res.data)
        // cateLeftList
        var appletsList = [];
        var rightShopList = [];
       if(res.data){

        var json = {selectNums: 0, name: "会员权益", id: 9999}
        appletsList.push(json);

        for(var i = 0;i < res.data.length;i++){
            var rightItem = {};
            var item = res.data[i];
            rightItem.storeCid = 9999;
            rightItem.id = item.productId;
            rightItem.image = item.productImage;
            // rightItem.price = item.productPrice;
            // rightItem.price = item.originalPrice;
            rightItem.price = item.price;
            rightItem.realPrice = item.price;
            rightItem.title = item.productName;
            rightItem.surplusUse = item.surplusUse;
            rightItem.surplusUseFixed = item.surplusUse;
            rightItem.dishAttrList = item.dishAttrList;
            rightItem.skuList = item.skuList;
            rightItem.num = item.surplusUse;
            rightShopList.push(rightItem);
        }

       }
       that.setData({
        rightShopList:rightShopList,
        appletsList:appletsList,
       },()=>{
        //    console.log('ddd----ff----',that.data.rightShopList);
        console.log('在profitShopFixDataFunc函数内')
        that.dealOnceSurplusUseFunc();
       })


    })
},

dealOnceSurplusUseFunc(){

    const that = this
    let tempJson = {
        storeId: that.data.storeId,
        userId: that.data.userInfo.id,
        token: that.data.token,
        storeDeskId:that.data.TableId,
    }
  
    common.wxRequest(that.data.shareShopCar==2?'/cart/listByStoreSku':'/cart/listForStoreDeskSku', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
        console.log('aaa只请求一次获取已选商品的id和个数',res);
        if (res.status === 200) {
            // 仅执行一次(因权益商品接口也只执行一次),解决增减权益次数时，动态展示本次的剩余次数的问题
            that.dataDealOnceSurplusUseFunc(res.data.list);
        } else {
             // this.getHasSelectShopItemIdAndCountFunc();
             that.judgeSelectPersonFunc();// 测试时，屏蔽改行代码，要打开上一行代码
        }
    }, () => {
  
    })
},

dataDealOnceSurplusUseFunc(cardHasSelectList){
    var that = this;
    console.log('ggggg-',that.data.rightShopList);
        var finalDeal = that.data.rightShopList;
        console.log('拼接未处理---',finalDeal);
        for(var i = 0;i < finalDeal.length;i++){// 给历史选中增加selectNum和selectCardId属性
         var allItem = finalDeal[i];
         var tempSelectNum = 0
         for(var j = 0;j < cardHasSelectList.length;j++){// 购物车里面的所有商品
             var selectItem = cardHasSelectList[j];
             console.log('哈哈哈-------哈哈哈哈',selectItem.itemId,'---ddd--', selectItem);
             if(selectItem.itemId == allItem.id){// 购物车里面的商品id等于所有商品的某个id
                console.log('相等有出现---', allItem)
                console.log('选中有出现---', selectItem)
                 if(allItem.storeCid==9999){//权益商品，统计已选择的权益商品总个数
                    if(allItem.surplusUse>0){// 有次数(原始的)
                            // 选择了3个，剩余6个
                        if(allItem.surplusUse - selectItem.num>=0){//选择数大于等于剩余数
                           // 之前已加购带权益次数商品,再次进入小程序权益次数未处理问题
                           console.log('原始个数--', selectItem.num)
                           allItem.surplusUse = allItem.surplusUse - selectItem.num;
                           console.log('处理了--', allItem.surplusUse)
                    //        tempSelectNum = tempSelectNum + selectItem.num;
                    //  allItem.selectNum =  tempSelectNum;


                        //    console.log('ddd---fff',selectItem.num);
                        }else{//选择数小于等于剩余数
                            // console.log('选择数小于等于剩余数');
                        }

                    }else{// 没有次数
                    
                    }              
                 }else{     
                 }
             }
         }
     }
    //  console.log('处nnnn理后---',finalDeal);
         that.setData({
             rightShopList: finalDeal,
         },()=>{
            // console.log('一次处理--',that.data.rightShopList);
                     // this.getHasSelectShopItemIdAndCountFunc();
                     that.judgeSelectPersonFunc();// 测试时，屏蔽改行代码，要打开上一行代码
         })
    },
unionDataFunc(tempList,dealList){     
    var that = this;
        var finalDeal = [...that.data.rightShopList,...dealList];
        var appletsSelectCount = 0;
        for(var i = 0;i < finalDeal.length;i++){// 给历史选中增加selectNum和selectCardId属性
         var allItem = finalDeal[i];
         var tempSelectNum = 0
         for(var j = 0;j < that.data.getHasSelectShopItemIdAndCountList.length;j++){// 购物车里面的所有商品
             var selectItem = that.data.getHasSelectShopItemIdAndCountList[j];
             if(selectItem.itemId == allItem.id){// 购物车里面的商品id等于所有商品的某个id
                 if(allItem.storeCid==9999){//权益商品，统计已选择的权益商品总个数
                     appletsSelectCount = appletsSelectCount? (appletsSelectCount + selectItem.num):selectItem.num;
                    // 因为一个商品有多个sku，所以这里要做累加计算
                     tempSelectNum = tempSelectNum + selectItem.num;
                     allItem.selectNum =  tempSelectNum;

                     allItem.selectCardId = selectItem.id;
                 }else{
                    allItem.selectNum = allItem.selectNum? (allItem.selectNum + selectItem.num):selectItem.num;// 把当前购物车的某个商品的个数赋值给所有商品的某个商品的selectNum属性
                    allItem.selectCardId = selectItem.id;
                 }
             }
         }
     }
    //  console.log('处nnnn理后---',finalDeal);
  
         that.setData({
             cateLeftList: [...that.data.appletsList,...tempList],
             appletsSelectCount:appletsSelectCount,
             dealDefaultItemList: finalDeal, // 走到这里，已经加上了selectNum和selectCardId属性
         },()=>{
                 that.calFunc();
         })
    },
getNeedList(storeId){
    // console.log('storeId---参数',storeId);
    var that = this
    var tempJson = {
        storeId:storeId,
    }
    // console.log('getEatNeedGoodsList---参数',tempJson);
    common.get('/store/getEatNeedGoodsList', tempJson, res => {
        // console.log('2222---getEatNeedGoodsList---',res);
        var needTotalPrice = 0.00;
        // console.log('333',that.data.currentSelectNum);
        for(var i = 0;i < res.data.length;i++){
            var item = res.data[i];
            var json = {};
            if(item.eatStandards=="1"){// 按人头
                needTotalPrice = that.data.currentSelectNum *item.price + needTotalPrice;
            }
            if(item.eatStandards=="2"){// 按桌
                needTotalPrice = item.price + needTotalPrice;
            }
       


        }
        // console.log('4444');
// console.log('--needTotalPrice--',needTotalPrice);
// console.log('5555');
        that.setData({
            needTotalPrice:needTotalPrice,
            needList:res.data
        })
    })
},
numClick(e){
    let currentIndex = e.currentTarget.dataset.index
    // console.log(currentIndex);
    if(currentIndex==11&&this.data.recordFixed==false){
        this.setData({
            recordFixed:true
        })
        return;
    }
        this.setData({
            currentNum:currentIndex,
            currentSelectNum: currentIndex+1,
        })
},
sureBtn(){
    if(this.data.currentNum==null){
     return   common.showToast('请选择就餐人数~')
    }
    this.saveEatNumsFunc();
        },

        saveEatNumsFunc(storeId) {
            var that = this;
          
            // console.log('xxxx-');
            const param = {
                storeId,
                eatNums:this.data.currentSelectNum,
                storeDeskId:this.data.TableId,
                // employeeId: this.data.employeeUserId,
                // employeeId: "",
                userId: this.data.userInfo.id,
            }
            // console.log('jjj',param);
            common.post('/store/saveEatNums',
                param,
                res => {
                    // console.log('信息为--',res);
                    if (res.status === 200) {
                        that.toMealList(this.data.currentSelectNum);
                    }
                },
                () => {
                    // console.log('dsadsdsd');
                   
                })
        },
        toMealList(selectPerson){
            var that = this
            var tempJson = {
                storeId:this.data.storeId,
                // xpoint: this.data.lat,
                // ypoint: this.data.lon,
                xcFlag: '0' //是否含有携程门票 0不含有
            }
            common.get('/store/mainPageInfo', tempJson, res => {
                that.setData({
                   
                }, () => {
                    clearInterval(that.data.timer);
                    // console.log('url---++===',`/packageC/pages/scanMealList/scanMealList?storeId=${that.data.storeId}&TableId=${that.data.TableId}&deskName=${that.data.deskName}&name=${that.data.storeName}&currentSelectNum=${selectPerson}`);
                    wx.navigateTo({
                        url: `/packageC/pages/scanMealList/scanMealList?storeId=${that.data.storeId}&TableId=${that.data.TableId}&deskName=${that.data.deskName}&name=${that.data.storeName}&currentSelectNum=${selectPerson}`,
                    })
    
                })
                // console.log(res.data.store, "75456666665")
            })
        },
        guideFunc(value){
            const that = this
            // console.log('suoyoushuj---',that.data.allAttrValueList);
            if(value === 1){// 选规格--增加数量才执行
                // console.log('dddd--', value, 'fff',this.data.rightShopList)  
                const rightShopList = this.data.rightShopList;
                const shopItem = rightShopList.find(item => item.id === that.data.itemId && item.surplusUse === 0);
                // console.log('--shopItem---', shopItem)
                if (shopItem) {
                common.showToast('已到最大权益次数!');
                    return true;
                }
            }
            // console.log('currentDishFlavorStr---',that.data.currentDishFlavorStr);
    
            let tempJson = {
              dishFlavor:that.data.currentItem.id,
                // dishFlavor:that.data.currentDishFlavorStr,// checkedStr?checkedStr.slice(0, -1):''
                userId: that.data.userInfo.id,
                token: that.data.token,
                storeDeskId:that.data.TableId,
                itemId:that.data.currentGuideJson.id,
                num:value,// that.data.addCount
            }
            common.wxRequest(that.data.shareShopCar==2?'/cart/add':'/cart/addItemCartForStoreDesk', 'post', tempJson, 'application/x-www-form-urlencoded', function (res) {
                if (res.status === 200) {
                    // that.closeAddCart()
                    that.rightSurpususeFunc(that.data.itemId,value); 
                    that.getCartNum()  //获取
                    that.getHasSelectShopItemIdAndCountFunc();
                    // that.getLeftBadgeNum();
                    that.setData({
             
                        localGoodsCount:value==1?that.data.localGoodsCount++:that.data.localGoodsCount--,
                    })
                    if(value==1){
                        common.showToast('添加成功!')
                    }else{
                        common.showToast('刪除成功!')
                    }
                   that.getItemCartCountForStoreDeskFunc(that.data.currentItem.id);
                    // wx.showToast({
                    //     title: '添加成功!',
                    // })
                } else {
                    wx.showToast({
                        icon: 'loading',
                        title: res.msg ? res.msg : '添加失败',
                    })
                }
            })
        },

        onGuideMinus(e) {
            this.guideFunc(-1);

        },
        // onCountChange(event) {
        //     console.log('dsdasda=', event.detail);
        //     this.setData({
        //         localGoodsCountaaa:99
        //     })
        //   },
        onGuidePlus(e) {
  
         
            this.guideFunc(1);
        },

        shop_shang() {
            wx.navigateTo({
              // url="{{'../../Goods/goodsOrder/goodsOrderList/index?type=1'}}"
            //   url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
            url: '/packageA/pages/Goods/goodsOrder/goodsOrderList/index?type=1',
            })
          },
})